package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.staticdata.ServiceOfferConst;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 互联网专线产品全程要求完成时间
 * 产品变更,录入界面全程要求完成时间置空,其它沿用专线类产品处理逻辑
 */
@Service
public class InternetZxAllComplexTimeHandler extends AbstractAttrHandler {
    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        // TODO: 临时处理，二次业务第一次加载清空
        String firstInitLoading = querySceneInstService.getExtParameterValue(sceneInstId, "FirstInitLoading");
        if(ServiceOfferConst.service_offer_2826.equals(sceneInst.getServiceOfferId()) && KiteStringUtils.isEmpty(nodeCode) && KiteStringUtils.isEmpty(firstInitLoading)) {
            commonAttr.setValue(null);
            commonAttr.setValueDesc(null);
            setCommonAttr(commonAttr);
            operateSceneInstService.putExtParameter(sceneInstId, "FirstInitLoading", "T");
        }
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        if (KiteStringUtils.isNotEmpty(value) && value.length() == 10){
            value += " 23:59:59";
        }

        KiteInst kiteInst = querySceneInstService.getKiteInst(sceneInst.getCustId(), sceneInst.getRootInstType(), sceneInst.getRootInstId());
        List<DcPublic> dclist = DcPublicCache.get("20210719001");
        // 是否五大双线落地方产品，全程要求完成时间一直必填
        boolean flag = (dclist != null) && dclist.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
        if (!flag) {
            //获取页面勾选的操作类型
            List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");
            IOperateSceneCommonService operateSceneCommonService = SpringUtil.getBean(IOperateSceneCommonService.class);
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId,LocalKeyConsts.WHOLE_PROCESS_TIME);
            if(Objects.nonNull(kiteAttr)){
                if(!KiteListUtils.isEmpty(serviceOfferIdList)&&serviceOfferIdList.size()==1){
                    if(serviceOfferIdList.contains("1009")||serviceOfferIdList.contains("1080")){
                        kiteAttr.setIsNull("T");
                    }
                    else{
                        kiteAttr.setIsNull("F");
                    }
                }else {
                    kiteAttr.setIsNull("F");
                }
                operateSceneCommonService.setCommonAttr(sceneInstId,kiteAttr);
            }
        }

        // 变更业务的场景初始化过程中不校验
        if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(sceneInst.getServiceOfferId())
            && !KeyConsts.IFTRUE_T.equals(querySceneInstService.getExtParameterValue(sceneInstId, LocalKeyConsts.WHOLE_PROCESS_TIME))
            && !"workOrder".equals(querySceneInstService.getExtParameterValue(sceneInstId, "initSource"))) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }

        if (KiteStringUtils.isEmpty(value)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        //重提初始化不校验
        //fixme 可能导致频繁访问缓存,上线临时处理方案
        Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
        if (Objects.nonNull(extParams) && extParams.containsKey("nodeCode")) {
            return  super.apply(sceneInstId, fieldName, value, valueDesc);
        }


        String allCompleteTimePattern = "yyyy-MM-dd HH:mm:ss";
        String azCompleteTimePattern = "yyyy-MM-dd";
        Date curDate = getCurrentDate();


        Date allCompleteTime = null;
        if (KiteStringUtils.isNotEmpty(value)){
            try{
                allCompleteTime = DateUtils.parseStrToDate(value, allCompleteTimePattern);
            }catch (Exception e){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
            }


            String scenInstId = KiteWebContext.getContext().getCurrentSceneInstId();
            List<KiteProdInst> prodInstList = querySceneInstService.listProdInsts(scenInstId);
            for(KiteProdInst kiteProdInst : prodInstList){
                //A端要求完成时间
                String aCompleteTimeStr = kiteProdInst.getAttrValue("2_0000122");
                String zCompleteTimeStr = kiteProdInst.getAttrValue("2_0000123");
                List<String> list = new ArrayList<>();
                list.add(aCompleteTimeStr);
                list.add(zCompleteTimeStr);
                for(String complteTimeStr : list){
                    if(KiteStringUtils.isNotEmpty(complteTimeStr)){
                        Date completeDate = null;
                        try{
                            completeDate = DateUtils.parseStrToDate(complteTimeStr,azCompleteTimePattern);
                        }catch(Exception e){
                            ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
                        }

                        //AZ端完成时间需要小于全局完成当前时间
                        if(null != completeDate && DateUtil.compare(completeDate,allCompleteTime) >1){
                            BssException.throwOut(KeyConsts.LOG_MODULE, "", "A、Z端要求完成时间不能晚于全程要求完成时间");
                        }

                    }
                }
            }
        }

        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    public Date getCurrentDate(){
        Date toDay =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String toDayStr = sdf.format(toDay);
        Date newDate = null;
        try {
            newDate = sdf.parse(toDayStr);

        }catch (Exception e){
            return newDate;
        }
        return newDate;
    }
}
